using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;
using System.Data;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class PivotPlugin : MissionPlugin
    {
        [Package(Direction.Input, "Defines the origin table you like to transform.")]
        enum OriginData
        {
        }

        [Package(Direction.Input, "Defines the cross tabulations settings.")]
        enum PivotSettings
        {
            [Column(typeof(string), "Defines the column name of the origin table, which contains the values for the new pivot columns.")]
            ColumnX,
            [Column(typeof(string), "Defines the column name of the origin table, which contains the values for the new pivot rows.")]
            ColumnY,
            [Column(typeof(string), "Defines the column name of the origin table, which contains the values for the pivot values.")]
            ColumnZ
        }

        [Package(Direction.Output, "Defines the transformed table after cross tabulations.")]
        enum PivotTable
        {
        }

        [Plugin(PluginDevStatus.Production, "Pivot tables are also useful for quickly creating unweighted cross tabulations.")]
        public PivotPlugin()
        {
        }

        public override void Initialize()
        {         
            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }

        /// <summary>
        /// Generate new Source-content.
        /// </summary>
        protected override void Work()
        {
            DataTableReader pivotSettingsReader = this.GetDataReader(typeof(PivotSettings));
            pivotSettingsReader.Read();
            
            string pivotSettingColumnX = pivotSettingsReader[PivotSettings.ColumnX.ToString()].ToString();
            string pivotSettingColumnY = pivotSettingsReader[PivotSettings.ColumnY.ToString()].ToString();
            string pivotSettingColumnZ = pivotSettingsReader[PivotSettings.ColumnZ.ToString()].ToString();

            List<string> columnXValues = new List<string>();
            List<string> columnYValues = new List<string>();
            
            // we must define all the new columns for the pivot table first
            List<KeyValuePair<string, Type>> columnDefinitions = new List<KeyValuePair<string, Type>>();
            columnDefinitions.Add(new KeyValuePair<string, Type>(pivotSettingColumnX, typeof(string))); // (the very first column is X-Axis column name)

            DataTableReader originPackageReader = this.GetDataReader(typeof(OriginData));
            while (originPackageReader.Read())
            {
                // save all DISTINCT values from columnX
                string columnXTemp = originPackageReader[pivotSettingColumnY].ToString();
                if (false == columnXValues.Contains(columnXTemp))
                {
                    columnXValues.Add(columnXTemp);

                    columnDefinitions.Add(new KeyValuePair<string, Type>(columnXTemp, originPackageReader[pivotSettingColumnY].GetType()));
                }
            }
            this.CreateNewSchemaForPackage(typeof(PivotTable), columnDefinitions);

            // select all DISTINCT values from columnY
            originPackageReader = this.GetDataReader(typeof(OriginData));
            while (originPackageReader.Read())
            {
                string columnYTemp = originPackageReader[pivotSettingColumnX].ToString();
                if (false == columnYValues.Contains(columnYTemp))
                {
                    columnYValues.Add(columnYTemp);
                }
            }

            // loop all DISTINCT columnY values
            foreach (string columnYValueOn in columnYValues)
            {
                DataRow newRow = this.CreateNewRowFromPackage(typeof(PivotTable));
                newRow[0] = columnYValueOn;
                
                MissionPluginPackage originPackage = this.GetPackageByName(typeof(OriginData));
  
                // select all rows for this columnY
                foreach (DataRow rowOn in originPackage.Select(pivotSettingColumnX + "='" + columnYValueOn + "'"))
                {
                    string columnXName = rowOn[pivotSettingColumnY].ToString();

                    //Read each column to fill the DataTable
                    foreach (KeyValuePair<string, Type> columnXOn in columnDefinitions)
                    {
                        if (columnXOn.Key == columnXName)
                        {
                            ////If Sum of Values is True it try to perform a Sum
                            ////If sum is not possible due to value types, the value displayed is the last one read
                            //if (sumValues)
                            //{
                            //    try
                            //    {
                            //        newRow[columnXName] = Convert.ToDecimal(newRow[columnXName]) + Convert.ToDecimal(dr["ExtractedText"]);    //columnZ
                            //    }
                            //    catch
                            //    {
                            //        newRow[columnXName] = dr["ExtractedText"];   //columnZ
                            //    }
                            //}
                            //else
                            {
                                newRow[columnXName] = rowOn[pivotSettingColumnZ]; //columnZ
                            }
                        }
                    }
                }
                this.AddNewRowToPackage(typeof(PivotTable), newRow);
            }
        }
    }
}
